import os
import numpy as np
from .dcore import parse_classify_line


class FileLine:
    def __init__(self, file_list):
        self.name = os.path.basename(file_list)
        self.lines = self._load_list(file_list)

    def __len__(self):
        return len(self.lines)
    
    def __getitem__(self, index):
        return self.lines[index]

    def _load_list(self, file_list):
        print("loading %s ..." % (self.name))
        datas = []
        with open(file_list, 'r', encoding='utf-8') as f:
            for line in f.readlines():
                try:
                    data = self.parse(line.strip())
                    datas.append(data)
                except Exception as e:
                    print(str(e))
        print("loading %s done")
        return datas
    
    def get_line(self, index):
        try:
            line = self.lines[index]
        except Exception as e:
            print('index error: ', index, len(self.lines))
            line = []
        return line

    def parse(self, line):
        return line.split()


class ClassifyDataset(FileLine):
    def __init__(self, num_classes, image_list, image_root=""):
        super(ClassifyDataset, self).__init__(image_list)
        self.num_classes = num_classes
        self.image_root = image_root

    def __getitem__(self, index):
        line = self.lines[index]
        return parse_classify_line(line, self.num_classes, self.image_root)